package com.quanyan.club.operate.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by zhuo.shi on 2016/12/7.
 * 抽奖概率计算
 */
public class LotteryRateListUtil<T> {

    public class ContinueRateList {

        private double minRate;
        private double maxRate;

        public ContinueRateList(double minRate, double maxRate){
            this.minRate = minRate;
            this.maxRate = maxRate;
        }

        public boolean hitRate(double rate){
            return  (minRate < rate && maxRate >= rate);
        }
    }

    private double maxRate;
    private Map<Integer, ContinueRateList> continueRateListMap = new ConcurrentHashMap<>();

    public LotteryRateListUtil(Map<Integer, Double> map){

        if (map.isEmpty()){
            throw new IllegalArgumentException("抽奖概率集合不能为空");
        }

        Set<Integer> keySet = map.keySet();
        double minRate = 0d;
        for (Integer index : keySet){
            double rate = map.get(index);
            minRate = maxRate;
            maxRate += rate;

            ContinueRateList continueRateList = new ContinueRateList(minRate, maxRate);
            continueRateListMap.put(index, continueRateList);
        }
    }

    public int hitLotteryRate(){
        Random random = new Random();
        double r = random.nextDouble();
        while (r == 0d){
            r = random.nextDouble();
        }

        double rate = r * maxRate;

        Set<Integer> keySet = continueRateListMap.keySet();
        for (Integer index : keySet){
            ContinueRateList continueRateList = continueRateListMap.get(index);
            if (continueRateList.hitRate(rate)){
                return index;
            }
        }
        return  -1;
    }

//    public static void main(String[] args) {
//        Map<Integer, Double> data = new HashMap<>();
//        data.put(0, 0.004d);
//        data.put(1, 4d);
//        data.put(2, 5d);
//        data.put(3, 10d);
//        data.put(4, 30d);
//        data.put(5, 50d);
//
//        LotteryRateListUtil lotteryRateListUtil = new LotteryRateListUtil(data);
//
//        Map<Integer, Integer> sy = new HashMap<>();
//        for (int i = 0; i < 1; i++){
//            Integer prizeId = lotteryRateListUtil.hitLotteryRate();
//            if (!sy.containsKey(prizeId)){
//                sy.put(prizeId, 1);
//            }else {
//                sy.put(prizeId, sy.get(prizeId)+1);
//            }
//        }
//        System.out.println(sy);
//    }
}
